package com.zqwh.xtool.activity;

import android.content.Intent;
import android.os.BatteryManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.zqwh.xtool.R;
import com.zqwh.xtool.ToolsApp;
import com.zqwh.xtool.domain.UserVO;
import com.zqwh.xtool.utils.ZqwhUtils;
import com.zqwh.yj.sdk.utils.BxwVoiceUtil;
import com.zqwh.yj.sdk.utils.ByteUtils;
import com.zqwh.yj.sdk.utils.LogUtils;
import com.zqwh.yj.sdk.utils.SerialPortUtils;
import com.zqwh.yj.sdk.utils.StringUtils;
import com.zqwh.yj.sdk.utils.ToastUtils;
import com.zqwh.yj.sdk.utils.httpRequest.subscribers.NetCallback;

import static com.zqwh.xtool.ToolsApp.gDevNo;
import static com.zqwh.xtool.ToolsApp.gNFCModel;
import static com.zqwh.xtool.ToolsApp.gUser;
import static com.zqwh.xtool.ToolsApp.gUserModel;
import static com.zqwh.xtool.config.BaseConfig.STAY_TIME;

public class LoginActivity extends BaseActivity {
    private static final int MSG_WHAT_READ_CARD = 0;
    private static final int MSG_WHAT_GET_BATTERY_CAPACITY = 1;
    private static final int MSG_WHAT_HIDE_DIALOG = 2;

    private TextView tvDevNo;
    private Button btnLoginAccount;
    private Button btnLoginCard;

    private EditText edtUsername;
    private EditText edtPassword;
    private TextView tvCapacity;

    private Boolean isCardWaiting = true;
    private String cardNo = "";

    private int batteryCapacity = 100;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login_box);

        setNFC();
        setView();
        setViewDialog();
        setClickListener();
        getBattery();
    }

    private void getBattery() {
        mHandler.sendEmptyMessageDelayed(MSG_WHAT_GET_BATTERY_CAPACITY, 10*1000);
    }

    @Override
    protected void onResume() {
        super.onResume();
        isCardWaiting = true;
    }

    @Override
    protected void onStop() {
        super.onStop();
        isCardWaiting = false;
    }

    private void setView() {
        btnLoginAccount = findViewById(R.id.btn_login_account);
        btnLoginCard = findViewById(R.id.btn_login_card);
        edtUsername = findViewById(R.id.edt_username);
        edtPassword = findViewById(R.id.edt_password);
        tvDevNo = findViewById(R.id.tv_no);
        tvCapacity = findViewById(R.id.tv_capacity);

        tvDevNo.setText("NO:"+gDevNo);
    }

    private void setClickListener() {
        btnLoginCard.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LogUtils.logout("Click : login by card");
                showZqwhDialogLoginCard();
            }
        });

        btnLoginAccount.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LogUtils.logout("Click : login by account");
                loginAccount();
            }
        });
    }

    private void gotoOptionsActivity(int delayed) {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                startActivity(new Intent(LoginActivity.this, LendReturnActivity.class));
                hideMyDialog();
            }
        }, delayed);
    }

    private void showZqwhDialogLoginCard() {
        String title = getResources().getString(R.string.login_by_card);
        String content = getResources().getString(R.string.put_ic_card);
        showMyDialog(title, content, null, null, 1, false);
        isCardWaiting = true;
        mHandler.sendEmptyMessageDelayed(MSG_WHAT_HIDE_DIALOG, 6000);
    }

    private void loginAccount() {
        if (batteryCapacity < 10){
            ToastUtils.showLongToast(LoginActivity.this, "电量过低，请充电后使用");
            return;
        }
        String username = edtUsername.getText().toString();
        String password = ZqwhUtils.md5(ZqwhUtils.md5(ZqwhUtils.md5(edtPassword.getText().toString())));
        if (StringUtils.isEmpty(username)){
            String text = getResources().getString(R.string.enter_your_username);
            ToastUtils.showLongToast(LoginActivity.this, text);
        }else if (StringUtils.isEmpty(password)){
            String text = getResources().getString(R.string.enter_your_password);
            ToastUtils.showLongToast(LoginActivity.this, text);
        }else {
            gUserModel.signInByAccount(ToolsApp.getDevId(), username, password, new NetCallback<UserVO>() {
                @Override
                public void onSuccess(UserVO user) {
                    edtUsername.setText("");
                    edtPassword.setText("");
                    if (user != null) {
                        gUser = user;
                        startActivity(new Intent(LoginActivity.this, LendReturnActivity.class));
                    }else {
                        String text = getResources().getString(R.string.login_failed);
                        ToastUtils.showLongToast(LoginActivity.this, text);
                    }
                }

                @Override
                public void onError(String msg) {
                    String text = getResources().getString(R.string.login_failed);
                    ToastUtils.showLongToast(LoginActivity.this, text);
                }
            });
        }
    }

    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if (msg.what == MSG_WHAT_GET_BATTERY_CAPACITY){
                BatteryManager manager = (BatteryManager) getSystemService(BATTERY_SERVICE);
                manager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CHARGE_COUNTER);
                manager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CURRENT_AVERAGE);
                manager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CURRENT_NOW);
                int capacity = manager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);
                tvCapacity.setText("当前电量："+capacity+"%");
                batteryCapacity = capacity;
                mHandler.sendEmptyMessageDelayed(MSG_WHAT_GET_BATTERY_CAPACITY, 10*1000);
            }
            if (msg.what == MSG_WHAT_READ_CARD){
                if (isCardWaiting) {
                    isCardWaiting = false;
                    BxwVoiceUtil.beeVoice(LoginActivity.this);
                    final String title = getResources().getString(R.string.login_by_card);
                    String content = getResources().getString(R.string.verifying_card_no);
                    showMyDialog(title, content, null, null, 1, false);
                    mHandler.removeMessages(MSG_WHAT_HIDE_DIALOG);
                    LogUtils.logout("Card NO : "+cardNo);
                    if (batteryCapacity < 10){
                        ToastUtils.showLongToast(LoginActivity.this, "电量过低，请充电后使用");
                    }else {
                        gUserModel.signInByCardNo(ToolsApp.getDevId(), cardNo, new NetCallback<UserVO>() {
                            @Override
                            public void onSuccess(UserVO user) {
                                gUser = user;
                                edtUsername.setText("");
                                edtPassword.setText("");
                                gotoOptionsActivity(STAY_TIME);
                                isCardWaiting = true;
                            }

                            @Override
                            public void onError(String msg) {
                                showMyDialog(title, "登录失败", null, null, 1, true, STAY_TIME);
                                isCardWaiting = true;
                            }
                        });
                        cardNo = "";
                    }
                }
            }else if (msg.what == MSG_WHAT_HIDE_DIALOG){
                hideMyDialog();
                isCardWaiting = true;
            }
            return false;
        }
    });

    void setNFC(){
        gNFCModel.setOnDataReceiveListener(new SerialPortUtils.OnDataReceiveListener() {
            @Override
            public void onDataReceive(byte[] buffer, final int size) {
                if (size == 9) {
                    StringBuffer sb = new StringBuffer();

                    for(int i=0; i < size; i++){
                        String hexStr = Integer.toHexString(buffer[i]&0xFF);
                        if (hexStr.length() < 2){
                            hexStr = "0" + hexStr;
                        }
                        sb.append(hexStr);
                    }

                    cardNo = sb.substring(6, 14).toUpperCase();

                    mHandler.sendEmptyMessage(MSG_WHAT_READ_CARD);
                }
            }
        });
    }
}
